//
//  PicturePickerController.swift
//  picturePickerView
//
//  Created by sunjinliang on 15/12/17.
//  Copyright © 2015年 sunjinliang. All rights reserved.
//

import UIKit

private let PicturePickerIdentifier = "PicturePickerIdentifier"

class PicturePickerController: UICollectionViewController {
   var pictures = [UIImage]()
    var seletcorIndex = 0
    let pictureMaxCount = 3
    
    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1)
        self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: PicturePickerIdentifier)

    }
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    init(){
        
        let picturePickerLayout = PicturePickerLayout()
        super.init(collectionViewLayout: picturePickerLayout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    ///自定义布局类
    private class PicturePickerLayout : UICollectionViewFlowLayout{
        
        private override func prepareLayout() {
            let margin  = UIScreen.mainScreen().scale * 4
            let count: CGFloat = 4
            let w = ((collectionView?.bounds.width)!-(count + 1) * margin) / count
            itemSize = CGSizeMake(w, w)
            minimumInteritemSpacing = margin
            minimumLineSpacing = margin
            collectionView?.bounces = true
            collectionView?.showsHorizontalScrollIndicator = false
            sectionInset =  UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        }
        
        
    }

    
    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return pictures.count+1
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PicturePickerIdentifier, forIndexPath: indexPath) as? PicturePickerCell
//         cell!.backgroundColor = UIColor.greenColor()
         cell?.pictureDelegate = self
        cell?.image = indexPath.item < pictures.count ? pictures[indexPath.item]:nil
        cell?.hidden = indexPath.item == pictureMaxCount
        return cell!
    }



}
///实现cell的代理方法
extension PicturePickerController : PicturePickerCellDelegate{
    func PicturePickerCellDidaddPicture(cell: PicturePickerCell) {
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            print("没有权限访问相册")
            return
        }
        seletcorIndex = (collectionView?.indexPathForCell(cell)?.item)!
        let picker = UIImagePickerController()
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
        
    }
    func PicturePickerCellDidremovePicture(cell: PicturePickerCell) {
        let indexPath = collectionView?.indexPathForCell(cell)
        pictures.removeAtIndex((indexPath?.item)!)
         collectionView?.deleteItemsAtIndexPaths([indexPath!])
        if pictures.count < pictureMaxCount - 1{
            return
        }
        let newIndexpath = NSIndexPath(forItem: pictureMaxCount - 1, inSection: 0)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            self.collectionView?.reloadItemsAtIndexPaths([newIndexpath])
        }
    }
}
//手机相册的代理方法
extension PicturePickerController : UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let image : UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        let newImage = image.scaleToWidth(600)
        if seletcorIndex >= pictures.count{
        pictures.append(newImage)
        }else{
            pictures[seletcorIndex] = newImage
        }
        dismissViewControllerAnimated(true, completion: nil)
        collectionView?.reloadData()
    }
}
@objc
protocol PicturePickerCellDelegate {
    optional func PicturePickerCellDidaddPicture(cell: PicturePickerCell)
    optional func PicturePickerCellDidremovePicture(cell: PicturePickerCell)
}
 class PicturePickerCell: UICollectionViewCell{
    var image: UIImage? {
        didSet{
            addButton.setImage(image == nil ?UIImage(named: "compose_pic_add"):image , forState: UIControlState.Normal)
            removeButton.hidden = image == nil
        }
    }
    private lazy var addButton: UIButton = {
       let btn = UIButton(imageName: "compose_pic_add", backImageName: nil)
        btn.addTarget(self, action: "addButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
  @objc  private lazy var removeButton : UIButton = {
        let btn = UIButton(imageName: "compose_photo_close", backImageName: nil)
        btn.addTarget(self, action: "removeButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    weak var pictureDelegate: PicturePickerCellDelegate?
    override init(frame: CGRect){
        
       super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func addButtonClick(btn:UIButton){
        pictureDelegate?.PicturePickerCellDidaddPicture?(self)
        print("添加图片")
    }
    @objc func removeButtonClick(btn:UIButton){
        pictureDelegate?.PicturePickerCellDidremovePicture?(self)
        print("删除图片")
    }

    private func setupUI(){
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        addButton.frame = bounds

        addButton.imageView?.contentMode = .ScaleAspectFill
        removeButton.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(contentView.snp_right)
            make.top.equalTo(contentView.snp_top)
        }


    }
    
}